<template>
  <!-- 素材管理 -->
  <div class="p-2">
    <!-- 头部搜索 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="素材标题" prop="title" style="width: 300px">
              <el-input v-model.trim="queryParams.title" placeholder="请输入" clearable />
            </el-form-item>

            <el-form-item label="素材类型" prop="type" style="width: 170px">
              <el-select v-model="queryParams.type" placeholder="请选择" clearable>
                <el-option v-for="dict in options" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="素材状态" prop="enable" style="width: 160px">
              <el-select v-model="queryParams.enable" placeholder="请选择" clearable>
                <el-option v-for="dict in euomurin" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-hasPermi="['gms:material:query']">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()"
              v-hasPermi="['gms:material:query']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="tuinseonui()"
              v-hasPermi="['gms:material:remove']">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"
            :search="true"></right-toolbar>
        </el-row>
      </template>
      <el-table :data="ordersListl" v-loading="loading" border max-height="550" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" width="190" v-if="columns[0].visible" />
        <el-table-column label="封面" align="center" width="120" v-if="columns[1].visible">
          <template #default="scope">
            <el-image style="width: 80px; height: 80px"
              :src="scope.row.cover "
              :preview-src-list="[scope.row.cover]" fit="contain" :preview-teleported="true" />
          </template>
        </el-table-column>
        <el-table-column label="素材类型" align="center" width="120" v-if="columns[2].visible">
          <template #default="scope">{{ chuonseuot(scope.row.type) }}</template>
        </el-table-column>
        <!-- <el-table-column label="素材状态" align="center" width="80" v-if="columns[2].visible">
          <template #default="scope">{{ composeFilters(scope.row.enable) }}</template>
        </el-table-column> -->
        <el-table-column label="商品卖点" align="center" width="150" :show-overflow-tooltip="true" v-if="columns[3].visible">
          <template #default="scope">{{ scope.row.sellingPoint }}</template>
        </el-table-column>
        <el-table-column label="素材标题" align="center" width="500" v-if="columns[4].visible">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" :content="item" placement="top"
              v-for="(item, index) in scope.row.titles" :key="index">
              <div class="onseuoc">{{ item }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="口播台词" align="center" width="500" v-if="columns[5].visible">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" :content="item" placement="top"
              v-for="(item, index) in scope.row.spokenLines" :key="index">
              <div class="onseuoc">{{ item }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" width="60" v-if="columns[6].visible" />
        <el-table-column label="图片数量" align="center" prop="imageNum" width="80" v-if="columns[7].visible" />

        <el-table-column label="视频数量" align="center" prop="videoNum" width="80" v-if="columns[8].visible" />

        <el-table-column fixed="right" label="素材状态" prop="enable" align="center" width="80" v-if="columns[9].visible">
          <template #default="scope">
            <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0" @change="approve(scope.row)"
              :disabled="enableFlag"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" fixed="right" align="center" width="150" v-if="columns[10].visible">
          <template #default="scope">{{ scope.row.createTime.slice(0, -3) }}</template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="150" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="内容" placement="top">
              <el-button link type="primary" icon="View" @click="handleDetails(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['gms:material:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="tuinseonui(scope.row)"
                v-hasPermi="['gms:material:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" @pagination="getList" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" />
    </el-card>
  </div>
</template>

<script setup lang="ts" name="Material">
import { listMaterial, delMaterial, enableMaterial } from '@/api/operates/material/index';
import { MaterialQuery, MaterialVO } from '@/api/operates/material/types';
import { fa } from 'element-plus/es/locale';
import useUserStore from '@/store/modules/user';
const permissions = useUserStore().permissions;
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const columns = ref<FieldOption[]>([
  { key: 0, label: `ID`, visible: true, children: [] },
  { key: 1, label: `封面`, visible: true, children: [] },
  { key: 2, label: `素材类型`, visible: true, children: [] },
  { key: 3, label: `商品卖点`, visible: true, children: [] },
  { key: 4, label: `素材标题`, visible: true, children: [] },
  { key: 5, label: `口播台词`, visible: true, children: [] },
  { key: 6, label: `排序`, visible: true, children: [] },
  { key: 7, label: `图片数量`, visible: true, children: [] },
  { key: 8, label: `视频数量`, visible: true, children: [] },
  { key: 9, label: `素材状态`, visible: true, children: [] },
  { key: 10, label: `创建时间`, visible: true, children: [] },
])

const initFormData: MaterialVO = {
  id: '',
  cover: '',
  type: '',
  titles: [],
  spokenLines: [],
  sort: 0,
  enable: 0,
  videoNum: 0,
  imageNum: 0,
  createTime: '',
  sellingPoint: '',
}
const data = reactive<PageData<MaterialVO, MaterialQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: '',
    title: '',
    enable: '',
  },
  rules: {},
})
const { queryParams, form } = toRefs(data)

const ordersListl = ref<MaterialVO[]>([]);
const total = ref(0);
const loading = ref(true)
const showSearch = ref(true)
const enableFlag = ref(false)
const queryFormRef = ref<ElFormInstance>();
const ids = ref<Array<string | number>>([])
const multiple = ref(true)

/**
 * 查询的素材类型
 */
const options = [
  {
    value: 'GOODS',
    label: '商品素材',
  },
  {
    value: 'TASK',
    label: '任务素材',
  }
]

/**
 * 查询的启用禁用
 */
const euomurin = [
  {
    value: 1,
    label: '启用',
  },
  {
    value: 0,
    label: '禁用',
  }
]

/**
 * 过滤（是否启用禁用）
 * @param val 
 */
const composeFilters = (val: number) => {
  if (val === 1) {
    return '启用'
  } else if (val === 0) {
    return '禁用'
  }
}

/**
 * 过滤（素材类型）
 * @param val 
 */
const chuonseuot = (val: string) => {
  if (val === 'GOODS') {
    return '商品素材'
  } else if (val === 'TASK') {
    return '任务素材'
  }
}

/**
 * 素材添加
 */
const handleAdd = () => {
  router.push({ path: "material/add" });
}

/**
 * 素材修改
 */
const handleUpdate = (row: MaterialVO) => {
  const id = row.id;
  router.push({ path: `material/edit/${id}` });
}

/**
 * 素材详情
 */
const handleDetails = (row: MaterialVO) => {
  const id = row.id;
  router.push({ path: `material/details/${id}` });
}

/**
 * 多选框选中数据
 */
const handleSelectionChange = (selection: MaterialVO[]) => {
  ids.value = selection.map((item: MaterialVO) => item.id);
  multiple.value = !selection.length;
}

/**
 * 查询素材列表
 */
const getList = async () => {
  loading.value = true
  const res = await listMaterial(queryParams.value);
  ordersListl.value = res.data.list;
  total.value = res.data.total;
  loading.value = false;
}

/**
 * 素材删除按钮操作
 */
const tuinseonui = async (row?: MaterialVO) => {
  // console.log(row?.enable);
  if (row?.enable == 0) {
    try {
      const id = row?.id || ids.value.join(',');
      await proxy?.$modal.confirm(`是否确认删除`);
      await delMaterial(id);
      getList()
      proxy?.$modal.msgSuccess("操作成功");
    } catch (error) {
    }
  } else {
    proxy?.$modal.msgError('请先执行禁用操作');
  }
}

/**
 * 素材审核{启用/禁用}
 */
const approve = async (row: MaterialVO) => {
  try {
    let text = row.enable === 1 ? "启用" : "禁用";
    await proxy?.$modal.confirm(`是否确认${text}素材`);
    await enableMaterial(row.id);
    getList();
    proxy?.$modal.msgSuccess(text + "成功");
  } catch (error) {
    row.enable = row.enable === 1 ? 0 : 1;
  }
}
// 素材审核按钮的判断
const enableFn = () => {
  if (permissions[0] !== '*:*:*') {
    enableFlag.value = !permissions.includes('gms:material:updown')
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/**
 * 重置搜索
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

onMounted(() => {
  getList();
  enableFn();
});

onUpdated(() => {
  getList();
})
</script>

<style scoped>
.onseuoc {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  background-color: #409eff;
  color: #fff;
  border-radius: 20px;
  padding-left: 13px;
  margin-bottom: 10px;
  cursor: pointer;
  text-align: left;
}
</style>